package com.ex.advice;

import com.common.ResultData;
import com.ex.config.ExceptionConfigFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

@ControllerAdvice
public class GlobleExceptionHandler {

    @Autowired
    private ExceptionConfigFactory factory;

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultData error(HttpServletRequest request, HttpServletResponse response, HandlerMethod method, Exception ex) throws SQLException {
        factory.createExDomain(ex, request);
        return ResultData.error("系统异常，异常信息[" + ex.getMessage() + "]");
    }

//    @ExceptionHandler
//    public String handleGlobalException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception ex, Model model) throws IOException {
//        /*
//        	1.1. ajax请求
//            1.2. jsonp调用异常
//            1.3. 请求资源异常
//         */
//        PrintWriter writer = response.getWriter();
//        if(WebUtil.isAjaxRequest(request)){ // 判断是否是ajax请求
//            response.setContentType("");
//            response.setContentType("text/json; charset=utf-8"); //解决从服务器返回中文乱码问题
//            writer.println("ajax-exception");
//            writer.flush();
//        }else if( WebUtil.isJsonpRequest(request)){ // 判断是否是Jsonp请求
//            response.setContentType("text/json; charset=UTF-8"); //解决从服务器返回中文乱码问题
//            writer.println("jsonp请求异常");
//            writer.flush();
//        }else { // 请求资源信息
//            response.sendRedirect(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" +"api/ex/404");
//        }
//        return null;
//    }

}